package com.android.lovepick;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.android.lovepick.http.HttpThread;
import com.android.lovepick.util.BaseUtils;
import com.android.lovepick.util.Constant;

public class MyOrderActivity extends Activity
{
	private final static String MYORDER_TAG = "MyOrderActivity";
	private final static int JSON_PARSE_SUCCESS = 0;
	private final static int JSON_PARSE_FAIL = -1;

	private ListView lvMyOrder;
	private SimpleAdapter mAdapter = null;
	private String[] from = new String[] { "src", "dest", "goTime", "orderID",
			"money", "state" };
	private int[] to = new int[] { R.id.myorder_list_src,
			R.id.myorder_list_dest, R.id.myorder_list_gotime,
			R.id.myorder_list_orderid, R.id.myorder_list_money,
			R.id.myorder_list_state };

	private String jsonString = null;
	private ProgressDialog mDialog = null;
	/**
	 * 由json对象解析而得的订单数据
	 */
	private List<Map<String, String>> mOrders = null;
	private MyOrderHandler mHandler;

	/**
	 * 标识用户身份
	 * <ul>
	 * <li>0: 乘客</li>
	 * <li>1: 司机</li>
	 * </ul>
	 */
	private int iDriver = 0;
	private String mUserRole = "";

	/**
	 * 标识获取的订单数据是发布路线后返回的还是匹配路线后返回的
	 * <ul>
	 * <li>false: 发布路线</li>
	 * <li>true: 匹配路线</li>
	 * </ul>
	 */
	private boolean releaseOrRecommend = false;
	private HttpThread mThread = null;
	private boolean isRefresh = false;
	private MyOrderActivity mMyOrderContext = null;

	/**
	 * 订单操作标志, 默认值为-1
	 * <ul>
	 * <li>0: 删除订单</li>
	 * <li>1: 接受订单</li>
	 * <li>2: 确认订单</li>
	 * </ul>
	 * 其中
	 * <ul>
	 * <li>"删除", "确认"操作只可能出现在发布路线后的显示界面中;</li>
	 * <li>"接受"操作只可能出现在推荐路线后的界面显示中.</li>
	 * </ul>
	 */
	private int orderFlag = -1;

	/**
	 * 若当前页面列出的是匹配路线, 则保存所有匹配路线, MapViewActivity要用到此参数.
	 */
	public static List<Map<String, String>> recommendOrders = null;

	/**
	 * 匹配路线列表中被选中的那一项, MapViewActivity中要用到.
	 */
	public static Map<String, String> recommendOrder = null;

	@Override
	public void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		setContentView(R.layout.myorder);
		mMyOrderContext = MyOrderActivity.this;
		jsonString = this.getIntent().getStringExtra("myorder");
		iDriver = this.getIntent().getIntExtra("iDriver", 0);
		releaseOrRecommend = this.getIntent().getBooleanExtra(
				"release_or_recommend", false);

		findViews();
		mUserRole = ((0 == iDriver) ? "passenger" : "driver");
		getStringFromJson(jsonString);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.myorder, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case android.R.id.home:
				// NavUtils.navigateUpFromSameTask(this);
				return true;

			case R.id.menu_map:
				if (recommendOrders == null)
				{
					BaseUtils.showToast(MyOrderActivity.this, "没有推荐路线!");
				}
				else
				{
					Intent intent = new Intent(MyOrderActivity.this,
							MapViewActivity.class);
					startActivity(intent);
				}
				return true;

			case R.id.menu_refresh_orders:
				if (!releaseOrRecommend)
				{
					refreshOrders();
				}
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * 从json对象中获取订单数据
	 * 
	 * @param jsonString 存储订单数据的json字符串
	 */
	private void getStringFromJson(final String jsonString)
	{
		mHandler = new MyOrderHandler(mMyOrderContext);
		mDialog = new ProgressDialog(mMyOrderContext);
		mDialog.setTitle("解析订单数据");
		mDialog.setMessage("正在解析订单数据, 请稍候...");
		mDialog.show();
		new Thread(new Runnable()
		{

			public void run()
			{
				// TODO Auto-generated method stub
				mOrders = BaseUtils.parseJsonFromString(jsonString);
				if (null == mOrders)
				{
					Message msg = new Message();
					msg.what = JSON_PARSE_FAIL;
					mHandler.sendMessage(msg);
				}
				else
				{
					Log.i(MYORDER_TAG, "---mOrders info---");
					// Log.i(MYORDER_TAG, mOrders.toString());
					Message msg = new Message();
					msg.what = JSON_PARSE_SUCCESS;
					mHandler.sendMessage(msg);
				}
			}
		}).start();
	}

	private void findViews()
	{
		lvMyOrder = (ListView) this.findViewById(R.id.listview_myorder);
	}

	/**
	 * 对订单列表中的某一项进行处理, 处理前弹出对话框请用户确认.
	 * 
	 * @param flag 操作标志
	 *            <ul>
	 *            <li>0: 删除订单</li>
	 *            <li>1: 接受订单</li>
	 *            <li>2: 确认订单</li>
	 *            </ul>
	 * @param orderMap 待处理的订单项
	 */
	private void doOrders(int flag, Map<String, String> orderMap)
	{
		final String url;
		String dialogTitle = "";
		String positive = "";
		String negative = "取消";
		BaseUtils.DialogClickListener listener = null;
		StringBuilder strBuilder = new StringBuilder();

		strBuilder.append("订单号:" + orderMap.get("orderID"));
		strBuilder.append("\n");
		strBuilder.append("起点:" + orderMap.get("src"));
		strBuilder.append("\n");
		strBuilder.append("终点:" + orderMap.get("dest"));
		strBuilder.append("\n");
		strBuilder.append("出发时间:" + orderMap.get("goTime"));
		strBuilder.append("\n");
		strBuilder.append("付款:" + orderMap.get("money"));
		strBuilder.append("\n");

		switch (flag)
		{
			case 0:
				// 删除订单
				Log.i(MYORDER_TAG, "删除订单");
				url = Constant.HTTP_ORDER_DELETE_URL + "/"
						+ orderMap.get("orderID") + "/" + mUserRole;
				strBuilder.append("发布身份:" + mUserRole);
				strBuilder.append("\n");
				strBuilder.append("订单状态:" + orderMap.get("state"));
				dialogTitle = "删除订单?";
				positive = "删除";
				listener = new BaseUtils.DialogClickListener()
				{

					public void doPositiveClick()
					{
						// TODO Auto-generated method stub
						mDialog.setTitle("删除订单数据");
						mDialog.setMessage("正在删除订单数据, 请稍候...");
						mDialog.show();
						mThread = new HttpThread(mHandler,
								Constant.HTTP_METHOD_GET, url, null);
						mThread.start();
					}

					public void doNegativeClick()
					{
						// TODO Auto-generated method stub

					}
				};
				break;

			case 1:
				// 接受订单
				Log.i(MYORDER_TAG, "接受订单");
				url = Constant.HTTP_ORDER_ACCEPT_URL + "/"
						+ orderMap.get("money") + "/" + mUserRole + "/"
						+ orderMap.get("orderID");
				strBuilder.append("发布身份:" + mUserRole);
				dialogTitle = "接受订单?";
				positive = "接受";
				listener = new BaseUtils.DialogClickListener()
				{

					public void doPositiveClick()
					{
						// TODO Auto-generated method stub
						mDialog.setTitle("接受订单");
						mDialog.setMessage("正在处理订单数据, 请稍候...");
						mDialog.show();
						mThread = new HttpThread(mHandler,
								Constant.HTTP_METHOD_GET, url, null);
						mThread.start();
					}

					public void doNegativeClick()
					{
						// TODO Auto-generated method stub
					}
				};
				break;

			case 2:
				// 确认订单
				Log.i(MYORDER_TAG, "确认订单");
				url = Constant.HTTP_ORDER_ACCEPT_URL + "/"
						+ orderMap.get("money") + "/" + mUserRole + "/"
						+ orderMap.get("orderID");
				strBuilder.append("接受者:" + orderMap.get("state").split("|")[0]);
				dialogTitle = "确认订单?";
				positive = "确认";
				listener = new BaseUtils.DialogClickListener()
				{

					public void doPositiveClick()
					{
						// TODO Auto-generated method stub
						mDialog.setTitle("确认订单");
						mDialog.setMessage("正在处理订单数据, 请稍候...");
						mDialog.show();
						mThread = new HttpThread(mHandler,
								Constant.HTTP_METHOD_GET, url, null);
						mThread.start();
					}

					public void doNegativeClick()
					{
						// TODO Auto-generated method stub

					}
				};
				break;

			default:
				break;
		}

		// 弹出确认对话框
		BaseUtils.showAlertDialog2(mMyOrderContext, dialogTitle,
				strBuilder.toString(), positive, negative, listener);
	}

	private void refreshOrders()
	{
		Log.i(MYORDER_TAG, "刷新订单");
		isRefresh = true;
		// 刷新订单
		String url = Constant.HTTP_ORDER_RELEASE_URL + "/2/";
		mDialog.setMessage("刷新订单列表中, 请稍候...");
		mThread = new HttpThread(mHandler, Constant.HTTP_METHOD_GET, url, null);
		mThread.start();
		mDialog.show();
	}

	private static class MyOrderHandler extends Handler
	{
		private final String MYORDER_HANDLER_TAG = "MyOrderHandler";
		private final WeakReference<MyOrderActivity> mReference;
		private MyOrderActivity mActivity = null;
		private Map<String, String> mSelectedMap = null;

		public MyOrderHandler(MyOrderActivity activity)
		{
			mReference = new WeakReference<MyOrderActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg)
		{
			// 获取MyOrderHandler所引用的MyOrderAcitivity实例
			mActivity = mReference.get();
			switch (msg.what)
			{
				case JSON_PARSE_SUCCESS:
					Log.i(MYORDER_HANDLER_TAG, "json parse successful");
					mActivity.mDialog.dismiss();
					BaseUtils.showToast(mActivity, "解析数据成功!");
					if (mActivity.releaseOrRecommend)
					{
						recommendOrders = mActivity.mOrders;
						Log.i(MYORDER_HANDLER_TAG, "recommendOrders:"
								+ recommendOrders.toString());
					}
					mActivity.mAdapter = new SimpleAdapter(mActivity,
							mActivity.mOrders, R.layout.myorder_list,
							mActivity.from, mActivity.to);
					mActivity.lvMyOrder.setAdapter(mActivity.mAdapter);
					mActivity.lvMyOrder
							.setOnItemLongClickListener(mOrderItemLongClickListener);
					break;

				case JSON_PARSE_FAIL:
					Log.i(MYORDER_HANDLER_TAG, "json parse failed");
					mActivity.mDialog.dismiss();
					BaseUtils.showToast(mActivity, "解析数据失败!");
					break;

				case Constant.MSG_HTTP_SUCCESS:
					// ===================================================
					// 接受订单, 确认交易, 删除订单操作均有联网操作,
					// 然后根据HTTP返回的结果进行相应处理.
					// 但是每种操作成功后的返回值都不一样,
					// 因此此处需要根据操作标志来区分到底执行了哪种操作.
					// ===================================================
					Log.i(MYORDER_HANDLER_TAG, "get http result");
					String result = msg.getData().getString("http_result");
					Log.i(MYORDER_HANDLER_TAG, "http_result: " + result);
					mActivity.mDialog.dismiss();
					switch (mActivity.orderFlag)
					{
					// 删除订单
						case 0:
							if (result.equals("deleted!!!"))
							{
								BaseUtils.showToast(mActivity, "订单删除成功!");
								// 删除成功后将删除项从列表中移除, 同时刷新listview
								mActivity.mOrders.remove(mSelectedMap);
								mActivity.mAdapter.notifyDataSetChanged();
							}
							else
							{
								BaseUtils.showToast(mActivity, "订单删除失败!");
							}
							break;

						// 接受订单
						case 1:
							if (result.equals("accept!!!"))
							{
								BaseUtils.showToast(mActivity, "接受订单成功");
								// 订单接受成功后将该项从列表中删除
								mActivity.mOrders.remove(mSelectedMap);
								mActivity.mAdapter.notifyDataSetChanged();
							}
							else
							{
								BaseUtils.showToast(mActivity, "接受订单失败!");
							}
							break;

						// 确认订单
						case 2:
							if (result.equals("ack!!!"))
							{
								BaseUtils.showToast(mActivity, "确认订单成功!");
								mActivity.mOrders.remove(mSelectedMap);
								mActivity.mAdapter.notifyDataSetChanged();
							}
							else
							{
								BaseUtils.showToast(mActivity, "确认订单失败!");
							}
							break;

						default:
							break;
					}

					if (mActivity.isRefresh && result.startsWith("[{"))
					{
						mActivity.getStringFromJson(result);
					}

					break;

				case Constant.MSG_HTTP_ERROR:
					Log.i(MYORDER_HANDLER_TAG, "http error...");
					BaseUtils.showToast(mActivity, "网络连接错误!");
					mActivity.mDialog.dismiss();
					break;

				default:
					break;
			}
		}

		private AdapterView.OnItemLongClickListener mOrderItemLongClickListener = new AdapterView.OnItemLongClickListener()
		{
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3)
			{
				// TODO Auto-generated method stub
				mSelectedMap = mActivity.mOrders.get(arg2);
				String[] items = null;
				DialogInterface.OnClickListener dialogClickListener = null;

				if (!mActivity.releaseOrRecommend)
				{
					// 目前显示的是发布订单后返回的, 用户曾经发布的还未处理的订单
					Log.i(MYORDER_HANDLER_TAG, "我的路线");
					items = new String[] { "确认交易", "删除订单" };
					dialogClickListener = new DialogInterface.OnClickListener()
					{

						public void onClick(DialogInterface dialog, int which)
						{
							switch (which)
							{
								case 0:
									Log.i(MYORDER_HANDLER_TAG, "确认交易!");

									BaseUtils.showToast(mActivity, "确认交易!");
									String state = mSelectedMap.get("state");
									Log.i(MYORDER_HANDLER_TAG, "订单状态: " + state);
									BaseUtils.showToast(mActivity, state);
									if (state.contains("|"))
									{
										String[] tmp = state.split("|");
										if (tmp[1].equals("申请交易"))
										{
											mActivity.orderFlag = 2;
											mActivity.doOrders(2, mSelectedMap);
										}
									}
									else if (state.equals("未处理"))
									{
										BaseUtils.showToast(mActivity,
												"订单未被接受, 不能确认交易!");
									}

									break;

								case 1:
									Log.i(MYORDER_HANDLER_TAG, "删除订单!");
									mActivity.orderFlag = 0;
									mActivity.doOrders(0, mSelectedMap);
									break;
								default:
									break;
							}
						}
					};

				}
				else
				{
					// 目前显示的是在发布订单页面用户填写完订单信息后
					// 点击推荐路线按钮后所返回的推荐路线
					Log.i(MYORDER_HANDLER_TAG, "推荐路线");
					items = new String[] { "接受", "地图查看" };
					dialogClickListener = new DialogInterface.OnClickListener()
					{

						public void onClick(DialogInterface dialog, int which)
						{
							// TODO Auto-generated method
							// stub
							switch (which)
							{
								case 0:
									Log.i(MYORDER_HANDLER_TAG, "接受订单!");
									String state = mSelectedMap.get("state");
									Log.i(MYORDER_HANDLER_TAG, "订单状态: " + state);
									if (state.equals("未处理"))
									{
										mActivity.orderFlag = 1;
										mActivity.doOrders(1, mSelectedMap);
									}
									else if (state.contains("|"))
									{
										String[] tmp = state.split("|");
										if (tmp[0].equals("已接受"))
										{
											BaseUtils.showToast(mActivity,
													"订单已接受!");
										}
									}
									break;

								case 1:
									recommendOrder = mSelectedMap;
									Intent intent = new Intent(mActivity,
											MapViewActivity.class);
									mActivity.startActivity(intent);
									break;

								default:
									break;
							}

						}
					};
				}
				String title = "请选择操作";
				AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
				builder.setTitle(title);
				builder.setItems(items, dialogClickListener);
				AlertDialog dialog = builder.create();
				dialog.show();
				return true;
			}
		};

	}
}
